# -*- coding: utf-8 -*-
"""
@File    : qinghai_shengji_policy
@Author  : caojy
"""
import datetime
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class QinghaiShengjiPolicy(BaseTaxPolicySpider):
    name = 'qinghai_shengji_policy'

    province = '青海省'
    city = ''
    county = ''
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['青海省人民政府', '', 'http://www.qinghai.gov.cn/xxgk/xxgk/fd/zfwj/'],
            ['青海省人民政府', '', 'http://www.qinghai.gov.cn/xxgk/xxgk/fd/lzyj/gfxwj/szf/'],
            ['青海省人民政府', '', 'http://www.qinghai.gov.cn/xxgk/xxgk/fd/lzyj/gfxwj/szfb/'],
            ['青海省人民政府', '', 'http://www.qinghai.gov.cn/xxgk/1/4/'],
            ['青海省人民政府', '', 'http://www.qinghai.gov.cn/xxgk/1/6/'],
            ['青海省人民政府', '', 'http://www.qinghai.gov.cn/xxgk/1/7/'],
            ['青海省发展和改革委员会', '', 'http://fgw.qinghai.gov.cn/22/32/index.html'],
            ['青海省人力资源和社会保障厅', '', 'https://rst.qinghai.gov.cn/pages/zfxxgk/'],
            ['青海省商务厅', '', 'http://swt.qinghai.gov.cn/zf/fd/zc/xz/'],
            ['青海省文化和旅游厅', '', 'https://whlyt.qinghai.gov.cn/zwgk/zc/xzgfxwj'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//tr/td[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] | "
                "//li[@class='clearfix']//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=10]"
                ""):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jhtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""//script""").re_first(r"""createPageHTML\(\s*\"?(\d+),""") or response.xpath("""//script""").re_first(r"""createPage\(\s*\"?(\d+),""")
            print(response.url, "page:", total_page)
            url = response.url
            if 'index' not in response.url:
                url += 'index.html'
            for page_num in range(1, int(int(total_page) / 1 + 2)):
                yield response.follow(url.replace('index.html', f'index_{page_num}.html'),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl qinghai_shengji_policy".split())
